from channels.db import database_sync_to_async
from django.contrib.auth.models import AnonymousUser
from api.models import UserInfo


@database_sync_to_async
def get_user(token):
    user_object = UserInfo.objects.filter(token=token).first()
    try:
        if not user_object:
            return AnonymousUser()
        return user_object
    except UserInfo.DoesNotExist:
        return AnonymousUser()


class UserInfoAuthMiddleware:
    """
    Token authorization middleware for Django Channels 2
    """

    def __init__(self, inner):
        # Store the ASGI application we were passed
        self.inner = inner

    async def __call__(self, scope, receive, send):
        token = dict(scope['headers']).get(b'authorization', None)
        if not token:
            scope['user'] = AnonymousUser()
        else:

            scope['user'] = await get_user(token.decode())

        return await self.inner(scope, receive, send)
